package cn.edu.nsmc.utils;

import cn.edu.nsmc.common.utils.R;
import cn.edu.nsmc.config.Constant;
import cn.hutool.core.lang.UUID;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;

@Component
public class FileUtils {
    @Value("${upload.path}")
    private String urlPath;

    public void getFile(String filename, HttpServletResponse response) throws IOException {
        response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
        File file = new File(Constant.WorksheetTemplateFilepath + filename);
        long length = file.length();
        response.addHeader("Content-Length", String.valueOf(length));
//        response.addHeader("Content-Disposition",
//                "attachment;filename=" + URLEncoder.encode(path, "utf-8"));
        //表示以二进制流的形式返回
       // response.setContentType("application/octet-stream");
        //设置Content-Disposition为inline
        response.addHeader("Content-Disposition", "inline;filename="
                + URLEncoder.encode(filename, "utf-8").replaceAll("\\+", "%20"));
        //下面这行代码是解决浏览器预览文件时中文乱码的
        String type = filename.substring(filename.lastIndexOf("."));
        type = type.toLowerCase();
        response.setContentType(type + ";charset=UTF-8");
        response.addHeader("Content-Length", String.valueOf(length));
        OutputStream outputStream = response.getOutputStream();
        byte[] buff = new byte[1024];
        BufferedInputStream bis = null;
        FileInputStream inputStream = new FileInputStream(file);
        bis = new BufferedInputStream(inputStream);
        int i = bis.read(buff);
        while (i != -1) {
            outputStream.write(buff, 0, buff.length);
            outputStream.flush();
            i = bis.read(buff);
        }
        bis.close();
        outputStream.close();
    }
    public void getExcelFile(String filename, HttpServletResponse response) throws IOException {
        response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
        File file = new File("/network/"+ filename);
        long length = file.length();
        response.addHeader("Content-Length", String.valueOf(length));
        response.addHeader("Content-Disposition",
                "attachment;filename=" + URLEncoder.encode("新增数据模板.xlsx", "utf-8").replaceAll("\\+", "%20"));
        //表示以二进制流的形式返回
        response.setContentType("application/octet-stream");
        //下面这行代码是解决浏览器预览文件时中文乱码的
        OutputStream outputStream = response.getOutputStream();
        byte[] buff = new byte[1024];
        BufferedInputStream bis = null;
        FileInputStream inputStream = new FileInputStream(file);
        bis = new BufferedInputStream(inputStream);
        int i = bis.read(buff);
        while (i != -1) {
            outputStream.write(buff, 0, buff.length);
            outputStream.flush();
            i = bis.read(buff);
        }
        bis.close();
        outputStream.close();
    }

    String path = null;

    public String getSavePath() {
        if (path == null) {
//            ApplicationHome applicationHome = new ApplicationHome(this.getClass());
//            path = applicationHome.getDir().getParentFile()
//                    .getParentFile().getAbsolutePath() + "\\upload\\";
//            path = "/root/workspace/java/demo/upload/";
            path = Constant.WorksheetTemplateFilepath;
        }
        return path;
    }

    public R addFile(MultipartFile file) throws FileNotFoundException {
        if (file != null) {
            String fileName = UUID.randomUUID() + "." + file.getContentType()
                    .substring(file.getContentType().lastIndexOf("/") + 1);

            File fileDir = new File(getSavePath(), fileName);

            if (!fileDir.exists()) {
                fileDir.mkdir();
            }

            try {
                file.transferTo(fileDir);
            } catch (IOException e) {
                e.printStackTrace();
                return R.error("文件上传失败");
            }
            return R.ok().put("url", fileName).put("imgUrl",Constant.FILE_URL_PRE+fileName);
        }
        return R.error("File not found");
    }
}
